﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using Encoder = System.Drawing.Imaging.Encoder;

public partial class _Default : Page
{
    private Image ig;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ddlSize.Items.Clear();
            ddlCompress.Items.Clear();
            for (int i = 100; i >= 30; i--)
            {
                ddlCompress.Items.Add(i.ToString());
                ddlSize.Items.Add(i.ToString());
            }
            ddlSize.SelectedIndex = 0;
            ddlCompress.SelectedIndex = 0;
        }
    }

    private void DownloadFile(string path)
    {
        Response.Clear();
        Response.Charset = "UTF-8";
        Response.Buffer = true;
        EnableViewState = false;
        Response.ContentEncoding = Encoding.UTF8;
        string str = HttpUtility.UrlEncode(Path.GetFileName(path), Encoding.UTF8);
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + str);
        Response.ContentType = "application/unknow";
        Response.WriteFile(path);
        Response.Flush();
        Response.Close();
        Response.End();
    }

    public static bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag)
    {
        Image iSource = Image.FromFile(sFile);
        ImageFormat tFormat = iSource.RawFormat;
        int sW = 0, sH = 0;
        var tem_size = new Size(iSource.Width, iSource.Height);
        if (tem_size.Height > dHeight || tem_size.Width > dWidth)
        {
            if ((tem_size.Width*dHeight) > (tem_size.Height*dWidth))
            {
                sW = dWidth;
                sH = (dWidth*tem_size.Height)/tem_size.Width;
            }
            else
            {
                sH = dHeight;
                sW = (tem_size.Width*dHeight)/tem_size.Height;
            }
        }
        else
        {
            sW = tem_size.Width;
            sH = tem_size.Height;
        }
        var oB = new Bitmap(dWidth, dHeight);
        Graphics g = Graphics.FromImage(oB);
        g.Clear(Color.WhiteSmoke);

        // 设置画布的描绘质量
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(iSource, new Rectangle((dWidth - sW)/2, (dHeight - sH)/2, sW, sH), 0, 0, iSource.Width,
                    iSource.Height, GraphicsUnit.Pixel);
        g.Dispose();

        // 以下代码为保存图片时，设置压缩质量
        var eP = new EncoderParameters();
        var qy = new long[1];
        qy[0] = flag;
        var eParam = new EncoderParameter(Encoder.Quality, qy);
        eP.Param[0] = eParam;
        try
        {
            //获得包含有关内置图像编码解码器的信息的ImageCodecInfo对象。
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICIinfo = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICIinfo = arrayICI[x]; //设置JPEG编码
                    break;
                }
            }
            if (jpegICIinfo != null)
            {
                oB.Save(dFile, jpegICIinfo, eP);
            }
            else
            {
                oB.Save(dFile, tFormat);
            }
            return true;
        }
        catch
        {
            return false;
        }
        finally
        {
            iSource.Dispose();
            oB.Dispose();
        }
    }

    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            try
            {
                string sourcePath = FileUpload1.PostedFile.FileName;
                string fileType = Path.GetExtension(sourcePath);
                if (fileType.ToLower() == ".jpg" || fileType.ToLower() == ".jpeg" || fileType.ToLower() == ".bmp" ||
                    fileType.ToLower() == ".png")
                {
                    string newPath = Server.MapPath("temp");
                    if (!Directory.Exists(newPath))
                    {
                        Directory.CreateDirectory(newPath);
                    }
                    newPath = newPath + "\\" + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + fileType;
                    FileUpload1.PostedFile.SaveAs(newPath);
                    ig = Image.FromFile(newPath);
                    Session["path"] = Server.MapPath("temp") + "\\" + DateTime.Now.Second + fileType; //保存上传到服务器上的图片路径
                    Session["spath"] = newPath;
                    GetPicThumbnail(newPath, Session["path"].ToString(),
                                    Convert.ToInt32(ig.Height*(Convert.ToDouble(ddlSize.SelectedItem.Text)/100)),
                                    Convert.ToInt32(ig.Width*(Convert.ToDouble(ddlSize.SelectedItem.Text)/100)),
                                    int.Parse(ddlCompress.SelectedItem.Text));
                    ig.Dispose();
                    ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('压缩完毕！');</script>");
                }
                else
                {
                    ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('请选择图片格式的文件');</script>");
                }
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + ex.Message + "');</script>");
            }
        }
        else
        {
            ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('请选择图片位置！');</script>");
        }
    }

    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            if (Session["path"] == null)
            {
                ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('请上传图片！');</script>");
            }
            else
            {
                string path = Session["path"].ToString();
                DownloadFile(path);
            }
        }
        catch (Exception ex)
        {
            ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + ex.Message + "');</script>");
        }
    }
}